<template>
  <div>
    <div class="main">
      <van-field
        class="input_text"
        readonly
        label="证书名称"
        required
        v-model="form.CertName"
        name="CertName"
        is-link
        @click="goCertList"
      >
      </van-field>
      <van-field
        class="input_text"
        label="证书类别"
        required
        v-model="form.CertTypeName"
        readonly
      />
      <van-field
        label="证书编号"
        required
        v-model="form.UserCertCode"
        name="UserCertCode"
      >
      </van-field>
      <van-field
        label="员工"
        required
        readonly
        v-model="form.ChnName"
        class="input_text"
        is-link
        name="ChnName"
        @click="goPeopleList"
      >
      </van-field>
      <van-field label="发证机构" v-model="form.CertOrg" name="CertOrg">
      </van-field>
      <van-field
        class="input_text"
        readonly
        clickable
        is-link
        required
        label="发证日期"
        v-model="form.PublishDate"
        name="PublishDate"
        @click="handleShow('PublishDate')"
      >
      </van-field>
      <van-field class="input_text" name="IsNeedReview" label="是否需要复审">
        <template #input>
          <van-checkbox v-model="form.IsNeedReview" shape="square" />
        </template>
      </van-field>
      <van-field
        v-if="form.IsNeedReview && !id"
        class="input_text"
        readonly
        clickable
         required
        name="ReviewDate"
        :value="form.ReviewDate"
        label="最近复审日期"
        placeholder="点击选择日期"
        @click="handleShow('ReviewDate')"
      >
      </van-field>
      <van-field
        v-if="form.IsNeedReview && !id"
        class="input_text"
        readonly
        clickable
        required
        name="NextReviewDate"
        :value="form.NextReviewDate"
        label="下次复审日期"
        placeholder="点击选择日期"
        @click="handleShow('NextReviewDate')"
      >
      </van-field>
      <van-field
        label="证书管理员"
        required
        readonly
        v-model="form.CertManagerChnName"
        class="input_text"
        is-link
        name="CertManagerChnName"
        @click="goCertPeopleList"
      >
      </van-field>
      <!-- <van-field label="证书附件" v-model="form.Attachs2" name="Attachs2">
      </van-field> -->
      <van-field label="证书附件" class="input_text_block">
        <template #input>
          <div
            v-for="(item, index) in fileList"
            :key="index"
            class="wrapper space-between mb-10"
          >
            <a style="color: blue" @click="_goEnclosure(item)">
              {{ item.AttName }}{{ item.AttExt }}</a
            ><van-icon name="cross" color="red" @click="delFile(index)" />
          </div>
          <!-- <div v-for="(item, index) in fileList"  :key="index" style="text-align:left;background-color: #ffffff!important">{{item.AttName}}{{item.AttExt}}</div> -->
          <van-uploader
            :max-count="2"
            @oversize="onOversize"
            :after-read="afterRead"
          >
            <van-button icon="plus" type="default" size="mini"
              >上传照片</van-button
            >
          </van-uploader>
          <van-button icon="plus" type="default" size="mini" @click="goFileList"
            >添加附件</van-button
          >
        </template>
      </van-field>
      <!-- <van-field
              class="input_text"
              name="uploader"
              label="整改图片"
            >
              <template #input>
                <van-uploader
                  v-model="fileList"
                  :max-count="2"
                  @oversize="onOversize"
                  :after-read="afterRead"
                >
                </van-uploader>
              </template>
            </van-field> -->
      <van-field
        label="备注"
        type="textarea"
        autosize
        v-model="form.Remarks"
        name="Remarks"
      >
      </van-field>
      <van-calendar
        color="#1989fa"
        v-model="showCalendar"
        :min-date="new Date('2000-01-01')"
          :max-date="new Date('2040-01-01')"
        @confirm="onConfirm"
      />
      <van-field
        v-if="form.IsNeedCheck"
        readonly
        clickable
        name="CheckDate"
        :value="form.CheckDay"
        label="最近检验日期"
        placeholder="点击选择日期"
        @click="handleShow('CheckDay')"
      />
      <van-field
        v-if="form.IsNeedCheck"
        readonly
        clickable
        name="NextCheckDate "
        :value="form.NextCheckDay"
        label="下次检验日期"
        placeholder="点击选择日期"
        @click="handleShow('NextCheckDay')"
      />

      <div class="btn_submit">
        <van-button block type="info" @click="submit"> 提交 </van-button>
      </div>
    </div>
    <van-dialog
      v-model="equpTypeShow"
      v-if="equpTypeShow"
      title="请选择"
      show-cancel-button
      :showConfirmButton="false"
      :showCancelButton="false"
      :closeOnClickOverlay="true"
    >
      <van-form>
        <van-field class="input_text" name="radio" label="">
          <template #input>
            <van-radio-group
              v-model="radio"
              @change="radioChange"
              direction="horizontal"
            >
              <template v-for="(item, index) in selectList">
                <van-radio :name="item.ID" :key="index">{{
                  item.Name
                }}</van-radio>
              </template>
            </van-radio-group>
          </template>
        </van-field>
        <div style="margin: 16px"></div>
      </van-form>
    </van-dialog>

    <van-popup
      v-model="showPopup"
      closeable
      round
      position="bottom"
      :style="{ height: '80%' }"
    >
      <div class="popup-title"></div>
      <div class="popup-content">
        <CertList @cb="_chooseCertList" />
      </div>
    </van-popup>
    <!-- 员工 -->
    <ExaminePeople
      title="选择人员"
      :show.sync="userPopup"
      @callback="_chooseUserPost"
    >
    </ExaminePeople>
    <!-- <van-popup
      v-model="userPopup"
      closeable
      round
      position="bottom"
      :style="{ height: '80%' }"
    >
      <div class="popup-title"></div>
      <div class="popup-content">
        <ExaminePeople @CallBack="_chooseUserPost" />
      </div>
    </van-popup> -->
    <!-- 证书管理员 -->
    <van-popup
      v-model="certPopup"
      closeable
      round
      position="bottom"
      :style="{ height: '80%' }"
    >
      <div class="popup-title"></div>
      <div class="popup-content">
        <CertPersonListItem @cbCert="_chooseCertPersonListItem" />
      </div>
    </van-popup>
     <!-- 查看附件详情 -->
        <van-popup
      v-model="showEnclosure"
       v-if="showEnclosure"
      closeable
      round
      position="bottom"
      :style="{ height: '80%' }"
    >
      <div class="popup-title"></div>
      <div class="popup-content">
        <Enclosure  :code="attCode"/>
      </div>
    </van-popup>
    <!-- 附件 -->
    <van-popup
      v-model="filePopup"
      closeable
      round
      position="bottom"
      :style="{ height: '80%' }"
    >
      <div class="popup-title"></div>
      <div class="popup-content">
        <FileList @cbFile="_chooseFileList" />
      </div>
    </van-popup>
  </div>
</template>

<script>
import { getDetail, editSubmit, addSubmit } from "@/api/cert";
import { uploadAttach } from "@/api/common";
import { formatDate, getDate, getTime } from "@/utils/getDate";
import CertList from "@/components/CertList/CertList.vue";
import Enclosure from "@/components/Enclosure/Enclosure.vue";
import ExaminePeople from "@/views/components/user/userChooseDialog.vue";
import CertPersonListItem from "@/components/CertPersonListItem/CertPersonListItem.vue";
import FileList from "@/components/FileList/FileList.vue";
import { mapGetters } from "vuex";
export default {
  components: {
    CertList,
    ExaminePeople,
    CertPersonListItem,
    FileList,
    Enclosure
  },
  computed: {
    ...mapGetters(["userName", "chnName"]),
  },
  data() {
    return {
      id: this.$route.query.id,
      menuList: [],
      mobile: "",
      message: "",
      radio: "1",
      checkbox: false,
      equpTypeShow: false,
      checkboxGroup: [],
      value: "",
      showCalendar: false,
      distList: {},
      selectList: [],
      form: {},
      selectName: "",
      selectKey: "",
      fileList: [],
      showPopup: false,
      userPopup: false,
      certPopup: false,
      filePopup: false,
      showEnclosure:false,
      attCode:''
    };
  },
  created() {
    if (this.$route.query.id) {
      this.getDetail();
    } else {
      this.form.CertManagerUserName = this.userName;
      this.form.CertManagerChnName = this.chnName;
    }

    //this.getDistList();
  },
  activated() {
    // if (this.$route.params.certFile) {
    // 	this.fileList.push({
    // 		AttCode: this.$route.params.certFile.AttCode,
    // 		AttExt: this.$route.params.certFile.AttExt,
    // 		AttName: this.$route.params.certFile.AttName,
    // 	})
    // }
    //将该页面的id和新获取的id进行比对，如果不一致，说明页面应该进行数据刷新
    //重新请求数据
    // if (this.$route.params.userlist) {
    //   const userlist = this.$route.params.userlist;
    //   let EquManagerChnName = [];
    //   let EquManagerUserName = [];
    //   userlist.forEach((item) => {
    //     EquManagerChnName.push(item.name);
    //     EquManagerUserName.push(item.code);
    //   });
    //   this.form.EquManagerChnName = EquManagerChnName.join(",");
    //   this.form.EquManagerUserName = EquManagerUserName.join(",");
    // }
  },
  methods: {
    onOversize(file) {
      Toast("文件大小不能超过 2M");
    },
    afterRead(file) {
      let params = new FormData(); //创建form对象
      params.append("file", file.file);
      uploadAttach(params)
        .then((res) => {
          this.fileList.push({
            AttCode: res.data.AttCode,
            AttExt: res.data.AttExt,
            AttName: res.data.AttName,
            AttFilePath: res.data.AttFilePath,
          });
          // res.data.forEach((item) => {
          //   // this.fileList.push(item.FilePath);
          // });
        })
        .catch((err) => {
          console.log("err", err);
        });
    },

    radioChange(names) {
      let select = this.selectList.filter((item) => item.ID == names);
      this.form[this.selectName] = select[0].Name;
      this.form[this.selectKey] = select[0].ID;
      this.equpTypeShow = false;
    },
    handleShow(name) {
      this.showCalendar = true;
      this.selectKey = name;
    },
    getDistList() {
      getDistList({ parentId: "MyList" }).then((res) => {
        this.distList = res.data;
      });
    },
    getDetail(certId) {
      let params = { id: this.id };
      getDetail(params).then((res) => {
        res.data.PublishDate = getDate(res.data.PublishDate);
        res.data.ReviewDate = getDate(res.data.ReviewDate);
        res.data.NextReviewDate = getDate(res.data.NextReviewDate);
        this.form = res.data;
        this.fileList = [];
        if (res.data.Attachs2) {
          let Attachs = res.data.Attachs2.split(";");
          console.log(Attachs, "Attachs");
          this.fileList = JSON.parse(res.data.Attachs2);
        }
      });
    },
    handleDialog(keyName, val, name, code) {
      this.selectList = [];
      this.selectList = this.distList[keyName];
      this.radio = val;
      this.selectName = name;
      this.selectKey = code;
      this.equpTypeShow = true;
    },
    // 部门
    goLocationItem() {
      this.$router.push("/Equipment/LocationItem");
    },

    onConfirm(date) {
      const dateTime = formatDate(date);
      this.form[this.selectKey] = getDate(dateTime);
      this.showCalendar = false;
    },
    // 删除
    delFile(index) {
      this.fileList.splice(index, 1);
    },

    submit() {
      if (!this.form.CertName) {
        return this.$toast("证书名称不能为空");
      }
      if (!this.form.UserCertCode) {
        return this.$toast("证书编号不能为空");
      }

      if (!this.form.ChnName) {
        return this.$toast("员工不能为空");
      }
      if (!this.form.PublishDate) {
        return this.$toast("发证日期不能为空");
      }
      if (!this.form.CertManagerChnName) {
        return this.$toast("证书管理员不能为空");
      }
      if (this.form.IsNeedReview && !this.$route.query.id) {
        if (!this.form.ReviewDate) {
          return this.$toast("最近复审日期不能为空");
        }
        if (!this.form.NextReviewDate) {
          return this.$toast("下次复审日期不能为空");
        }
      }

      let params = {
        Attachs2: JSON.stringify(this.fileList),
        ReviewDate: this.form.ReviewDate,
        PublishDate: this.form.PublishDate,
        UserCertCode: this.form.UserCertCode,
        ID: this.form.ID,
        UserName: this.form.UserName,
        CertManagerUserName: this.form.CertManagerUserName,
        CertCode: this.form.CertCode,
        NextReviewDate: this.form.NextReviewDate,
        Remarks: this.form.Remarks,
        CertOrg: this.form.CertOrg,
        IsNeedReview: this.form.IsNeedReview,
      };
      if (this.$route.params.id == 0) {
        addSubmit(params).then((res) => {
          this.$toast.success("新增成功");
          this.form = {
            ID: 0,
          };
          this.fileList = [];
          setTimeout(() => {
            this.$router.push("/Credential");
          }, 500);
        });
      } else {
        editSubmit(params).then((res) => {
          this.$toast.success("保存成功");
          setTimeout(() => {
            this.$router.push("/Credential");
          }, 500);
          // setTimeout(() => {
          //   this.$router.go("/Credential/Detail?certId="+this.$route.query.certId);
          // }, 500);
        });
      }
    },
    // 附件详情
    _goEnclosure(item) {
       this.attCode= item.AttCode 
      // console.log(item,'sdvfdvdcd')
      // this.$router.push({
      //   path: "/Credential/Enclosure",
      //   query: { attCode: item.AttCode },
      // });
        this.showEnclosure = true;
    },
    // 跳转选择项
    goEquipmentItem(codes) {
      this.$router.push({
        path: "/Equipment/EquipmentItem",
        query: { userId: codes },
      });
    },

    // 选择证书
    goCertList() {
      // this.$router.push({
      //   path: "/Credential/CertList",
      //   query: { id: this.id },
      // });
      // this.$router.push("/Credential/CertList");
      this.showPopup = true;
    },
    // 选择证书
    _chooseCertList(item) {
      // console.log(item,'item')
      if (item) {
        this.$set(this.form, "CertName", item.CertName);
        this.$set(this.form, "CertCode", item.CertCode);
        this.$set(this.form, "CertTypeName", item.CertTypeName);
      }
      this.showPopup = false;
    },
    // 选择员工

    goPeopleList() {
      // this.$router.push({
      //   path: "/Credential/PeopleList",
      //   query: { id: this.id },
      // });
      this.userPopup = true;
    },
    _chooseUserPost(item) {
      
      if (item) {
        this.$set(this.form, "ChnName", item.ChnName);
        this.$set(this.form, "UserName", item.UserName);
        this.userPopup = false;
      }
    },
    // 证书管理员
    goCertPeopleList() {
      // this.$router.push({
      //   path: "/Credential/CertPeopleList",
      //   query: { id: this.id },
      // });
      this.certPopup = true;
      // this.$router.push("/Credential/CertPeopleList");
    },
    _chooseCertPersonListItem(item) {
      
      if (item) {
        this.$set(this.form, "CertManagerChnName", item.ChnName);
        this.$set(this.form, "CertManagerUserName", item.UserName);
      }
      this.certPopup = false;
    },
    // 选择附件
    goFileList() {
      this.filePopup = true;
    },
    _chooseFileList(item) {
      console.log(item, "item");
      if (item) {
        this.fileList.push({
          AttCode: item.AttCode,
          AttExt: item.AttExt,
          AttName: item.AttName,
        });
      }
      this.filePopup = false;
    },
  },
};
</script>

<style lang="less" >
.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.block {
  width: 120px;
  height: 120px;
  background-color: #fff;
}
</style>
<style lang="less" scoped>
.space-between {
  justify-content: space-between;
}
</style>
